package org.jmh.gift.controller;


import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.jmh.gift.contants.PayConstants;
import org.jmh.gift.domain.AccountAlipay;
import org.jmh.gift.domain.PayOrder;
import org.jmh.gift.service.IAccountAlipayService;
import org.jmh.gift.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay/ali")
public class PayAliController {
    @Autowired
    private IAccountAlipayService accountAlipayService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private IPayOrderService payOrderService;

    @PostMapping("/alipay")
    public String aliPay(HttpServletRequest request)throws Exception{
        Map<String,String> params = new HashMap<String,String>();
        //获取参数
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        AccountAlipay accountAlipay = accountAlipayService.selectOne(new EntityWrapper<AccountAlipay>().eq("tenant_id", 0));
        boolean signVerified = AlipaySignature.rsaCheckV1(params, accountAlipay.getAlipayPublicKey(), "UTF-8", accountAlipay.getSignType());
        if(signVerified) {
            String trade_status = params.get("trade_status");
            String out_trade_no = params.get("out_trade_no");
            if (trade_status.equals("TRADE_SUCCESS")){
                PayOrder payOrder = payOrderService.selectOne(new EntityWrapper<PayOrder>().eq("uni_pay_order_sn", out_trade_no));
                params.put("businessId",payOrder.getBusinessId());
                params.put("businessType",payOrder.getBusinessType()+"");
                // 发送rocketmq事务消息
                Message<Map<String, String>> message = MessageBuilder.withPayload(params).build();
                TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(PayConstants.ALI_PAY_NOTIFY_TX_PRODUCER_GROUP, PayConstants.ALI_PAY_NOTIFY_TX_TOPIC + ":" + PayConstants.ALI_PAY_NOTIFY_TX_TAG, message, null);
                if(sendResult.getSendStatus() != SendStatus.SEND_OK || sendResult.getLocalTransactionState() != LocalTransactionState.COMMIT_MESSAGE){
                    return "失败";
                }
            }
                return "成功";
        }else
            return "失败";
    }

}
